<template>
  <div class="order-reply-container">
    <div class="content">
      <el-timeline class="first_pane">
        <el-timeline-item
          v-for="(activity, index) in activeList"
          :key="index"
          class="box-card"
          :color="color[index % 4]"
          :timestamp="activity.createTime"
          placement="top"
        >
          <el-card>
            <div class="card-header">
              <div class="c_network" :class="colorBg[index % 4]">
                {{ `【${activity.emp}】${activity.content}` }}
              </div>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
      <div v-if="currentPage * 10 < total" class="load-more" @click="getMoreData">
        加载更多数据
      </div>
      <div v-if="currentPage * 10 >= total" class="no-more"> 没有更多了 </div>
    </div>
    <div class="footer">
      <div v-if="!$route.query.isArchive" class="content_send_upload">
        <div
          ref="contenteditableInputs"
          placeholder="发送留言..."
          class="content"
          contenteditable="true"
          @focus="scrollHeight()"
        ></div>
        <div class="flex-justify-end">
          <h-link @click="sendInfoAction">发送</h-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, nextTick, reactive, PropType } from 'vue'
  import { useRoute } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import { getWorkLeaveMessageList, saveWorkLeaveMessage } from '@/api/order'
  import { orderAnnexUpload } from '@/api/upload'

  interface LeaveMessage {
    annex: string
    annexs: Array<string>
    avatar: string
    content: string
    createTime: string
    emp: string
    empId: string
    empType: number
    id: string
    visitTypes: any
    workId: string
    workNo: string
  }

  const props = defineProps({
    orderDetail: {
      type: Object as PropType<OrderDetail>,
      required: true,
    },
  })

  const colorBg = ['back_c4', 'back_c3', 'back_c2', 'back_c1']
  const color = ['#007cff', '#a06eff', '#00c0c0', '#e69103']
  const chatContentDiv = ref<HTMLDivElement | null>(null)
  const activeList = ref<Array<LeaveMessage>>([])
  const total = ref(0)
  let pageSize = ref(10)
  let currentPage = ref(1)
  const route = useRoute()
  let data = reactive({
    annex: [],
    content: '',
    visitTypes: [0],
    workId: props.orderDetail.id,
  })
  const imageUrls = ref([])
  const contenteditableInputs = ref<HTMLDivElement | null>(null)
  // 滚动到底部
  const scrollHeight = () => {
    setTimeout(() => {
      if (chatContentDiv.value) {
        chatContentDiv.value.scrollTop = chatContentDiv.value.scrollHeight
      }
    }, 100)
  }

  // 发送
  const sendInfoAction = async () => {
    // 获取去除首尾空格的内容
    let value = contenteditableInputs.value.innerHTML.trim()
    if (!value) {
      return ElMessage.error('请填写发送内容')
    }
    let img = []
    let imgIds = []
    let txt = /<div.*?>(.*?)<\/div>/gi
    let reg1 = /<img.*?title="(.*?)".*?>/gi
    let flag = value.match(reg1)
    if (value.match(txt)) {
      value = value.replace(txt, (item, $item) => {
        //找到图片做标书
        if ($item == '<br>') {
          return `\n`
        } else {
          return `\n${$item}`
        }
      })
    }
    // 过滤图片进行分割
    if (flag) {
      let content2 = value.replace(reg1, (item, $1) => {
        //找到图片做标书
        imgIds.push($1)
        return ``
      })
      imageUrls.value.filter((o) => {
        imgIds.filter((i) => {
          if (o.uid) {
            if (o.uid == i) {
              img.push(o)
            }
          } else {
            if (new Date(o.lastModifiedDate).getTime() == i) {
              img.push(o)
            }
          }
        })
      })
      data.content = content2
    } else {
      data.content = value
    }
    if (img.length > 0) {
      const res = await orderAnnexUpload(img)
      if (res.data.code === 20000) {
        data.annex = res.data.data.rows
        await saveWorkLeave()
      }
    } else {
      await saveWorkLeave()
    }
    data.annex = []
  }

  const emits = defineEmits(['updated'])
  /**
   * 保存留言
   */
  async function saveWorkLeave() {
    const res = await saveWorkLeaveMessage(data)
    if (res.data.code == 20000) {
      await getList()
      scrollHeight() //滚动到底部
      if (contenteditableInputs.value) {
        contenteditableInputs.value.innerHTML = ''
      }
      imageUrls.value = []
      emits('updated')
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
        })
    }
  }

  /**
   * 获取更多
   */
  const getMoreData = async () => {
    currentPage.value += 1
    const res = await getWorkLeaveMessageList(
      { limit: 10, page: currentPage.value },
      props.orderDetail.id,
    )
    if (res.data.code === 20000) {
      activeList.value = [...res.data.data.rows, ...activeList.value]
      total.value = Number(res.data.data.total)
    }
  }
  // 获取留言列表
  async function getList() {
    const res = await getWorkLeaveMessageList({ limit: 10, page: 1 }, props.orderDetail.id)
    if (res.data.success) {
      activeList.value = res.data.data.rows
      total.value = Number(res.data.data.total)
      nextTick(() => {
        scrollHeight()
      })
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
          duration: 4000,
        })
    }
  }

  // 复制粘贴
  async function handlePaste(event: ClipboardEvent) {
    const clipboardData = event.clipboardData
    if (!clipboardData) {
      return false
    }
    const pastedText = clipboardData.getData('text')
    event.preventDefault()
    if (contenteditableInputs.value) {
      contenteditableInputs.value.innerHTML += pastedText
    }
  }

  defineExpose({
    init: async () => {
      await getList()
      if (!route.query.isArchive) {
        await nextTick()

        if (contenteditableInputs.value) {
          contenteditableInputs.value.addEventListener('paste', handlePaste) // 监听粘贴事件
        }
      }
    },
  })
</script>

<style lang="scss" scoped>
  .order-reply-container {
    height: 100%;
    display: flex;
    flex-direction: column;

    .content {
      flex: 1;
      height: 0;
      overflow-y: auto;

      .load-more {
        margin-bottom: 12px;
        display: flex;
        justify-content: center;
        color: #007cff;
        cursor: pointer;
      }

      .no-more {
        margin-bottom: 12px;
        display: flex;
        justify-content: center;
        color: #606266;
      }
    }

    .footer {
      height: 144px;

      .content_send_upload {
        height: 100%;
      }
    }
  }

  .left_side {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    flex: 1;
    height: 0;

    .item_li {
      height: 100vh;
      overflow-y: auto;
      margin: 0 10px;
      width: 100%;
      scrollbar-width: none;
      /* Firefox */
      -ms-overflow-style: none;

      /* IE 10+ */
      &::-webkit-scrollbar {
        display: none;
        /* Chrome Safari */
      }

      .load_more {
        display: flex;
        align-items: center;
        justify-content: center;
        color: #999;
        font-size: 11px;
        margin-bottom: 12px;

        &:hover {
          color: #007cff;
          cursor: pointer;
        }
      }

      .on_more {
        display: flex;
        align-items: center;
        justify-content: center;
        color: #999;
        font-size: 11px;
        margin-bottom: 12px;
      }

      .li_c {
        .item_c {
          position: relative;
          right: 50%;
          transform: translateX(50%);
          font-size: 10px;
          color: #999;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .oneself_c {
          display: flex;
          flex-direction: column;
          align-items: flex-end;

          .top_note {
            display: flex;
            align-items: end;
            flex-direction: row-reverse;
            flex-direction: column;
            width: 100%;

            .content_c {
              max-width: 300px;
              margin: 8px 30px 20px 0;
              display: flex;
              flex-direction: column;
              gap: 4px;
              align-items: flex-end;

              .text_c {
                padding: 5px 8px;
                color: #333;
                white-space: pre-wrap;
                font-size: 12px;
                background-color: #e2e7f7;
                border-radius: 6px 0 6px 6px;
                display: inline-block;
              }

              .img_container {
                display: grid;
                grid-template-columns: auto;
                row-gap: 4px;
              }
            }

            .item_name {
              margin-right: 5px;
              font-size: 12px;
              color: #666;
            }
          }
        }

        .top_note {
          .user {
            display: flex;
            align-items: center;

            .avatar {
              width: 30px;
              height: 30px;
              border-radius: 50%;
            }

            .item_name {
              margin-left: 5px;
              font-size: 12px;
              color: #666;
            }
          }

          .content_c {
            margin: 8px 0 20px 30px;
            display: flex;
            flex-direction: column;
            gap: 4px;
            max-width: 300px;
            align-items: flex-start;

            .text_c {
              padding: 5px 8px;
              color: #333;
              white-space: pre-wrap;
              font-size: 12px;
              background-color: #e2e7f7;
              border-radius: 0 6px 6px 6px;
              // box-shadow: 0 0 1px 1px #00000022;
              word-wrap: break-word;
              word-break: break-all;
              display: inline-block;
            }

            .img_container {
              display: grid;
              grid-template-columns: auto;
              row-gap: 4px;
            }
          }
        }
      }
    }

    .chatInput {
      width: 100%;
      box-sizing: border-box;
    }
  }

  .f_content {
    width: 100%;
    box-sizing: border-box;
    background-color: #fff;

    .upload_send {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 8px;

      .btn_send {
        color: #00c0c0;
        font-size: 12px;
        cursor: pointer;
        margin-left: 8px;

        &:hover {
          color: #00c0c0ab;
        }
      }

      .btn_uploading {
        cursor: pointer;
        font-size: 16px;
      }
    }

    :deep(.el-textarea .el-input__count) {
      right: 40px;
    }

    [contenteditable]:focus {
      outline: none;
    }

    [contenteditable]:empty:before {
      content: attr(placeholder);
      color: #cccccc;
      font-size: 12px;
    }
  }

  .footer {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .content_send_upload {
      display: flex;
      flex-direction: column;
      gap: 8px;

      div.content {
        white-space: pre-wrap;
        font-size: 12px;
        word-wrap: break-word;
        word-break: break-all;
        display: inline-block;
        background-color: #f2f3f5;
        border-radius: 4px;
        box-sizing: border-box;
        padding: 8px;
        height: 120px;
        text-align: left;
        outline: none;
        overflow: auto;
      }

      div.content:empty:before {
        content: attr(placeholder);
        color: #a8abb2;
      }

      .btn_group {
        display: flex;
        justify-content: space-between;
      }
    }

    .visit_type {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;

      .visit_type_text {
        color: #000;
      }

      :deep(.el-checkbox) {
        height: 18px;
        margin: 0 !important;

        .el-checkbox__label {
          transform: scale(0.9);
          font-size: 12px;
          padding: 0;
        }
      }
    }
  }

  .box-card {
    padding-bottom: 20px;

    .back_c1 {
      background-color: #f5eee3;
      color: #e69103;
    }

    .back_c2 {
      background-color: #d2f7f7;
      color: #00c0c0;
    }

    .back_c3 {
      background-color: #eee9fa;
      color: #a06eff;
    }

    .back_c4 {
      background-color: #e4eef8;
      color: #007cff;
    }

    .c_network {
      padding: 4px 5px;
      display: inline-block;
      font-size: 12px;
    }

    .c_note {
      color: #999;
      margin: 8px 0;
    }

    :deep(.el-timeline-item__node--normal) {
      left: 0;
    }

    :deep(.el-timeline-item__tail) {
      left: 5px;
    }

    :deep(.el-timeline-item__wrapper) {
      padding-left: 20px;
      top: -5px;
    }
  }

  :deep(.el-card__header) {
    padding: 10px 0;
    margin: 0 10px;
  }

  :deep(.el-card__body) {
    padding: 10px;
    font-size: 12px;
  }

  :deep(.el-card) {
    border: none;
    width: 99%;
    border-radius: 0;

    &.is-always-shadow {
      box-shadow: 0 0 8px rgba(0, 0, 0, 0.12);
    }
  }
</style>
